package com.baitiaojun.bulletscreen.timer;

import com.baitiaojun.bulletscreen.util.BulletScreenConstantUtil;
import com.baitiaojun.bulletscreen.util.JsonUtil;
import com.baitiaojun.bulletscreen.websocket.BulletScreenWebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @类名 OnlineCountTimer
 * @描述 TODO
 * @作者 白条君
 * @创建日期 2023/1/2 18:27
 * @版本 1.0
 */
@Slf4j
@Component
public class OnlineCountTimer {

    @Scheduled(fixedRate = 5000)
    public void onlineCount() throws IOException {
        Map<String, BulletScreenWebSocketServer> bulletScreenMap = BulletScreenConstantUtil.BULLET_SCREEN_MAP;
        Set<Map.Entry<String, BulletScreenWebSocketServer>> entries = bulletScreenMap.entrySet();
        Map<Long, AtomicInteger> onlineCountMap = BulletScreenConstantUtil.ONLINE_COUNT_MAP;
        for (Map.Entry<String, BulletScreenWebSocketServer> entry : entries) {
            BulletScreenWebSocketServer webSocketHandler = entry.getValue();
            if (webSocketHandler.getSession().isOpen()) {
                webSocketHandler.sendMsg(JsonUtil.convertJsonString("count", onlineCountMap.get(webSocketHandler.getVideoId())));
                log.info("count:{}", onlineCountMap.get(webSocketHandler.getVideoId()));
            }
        }
    }
}
